/**
 * 初始化地球模型
 * 后期可在这更改地球模型
 */
import { SuperMap3D } from '@/utils/supermap3d';

export const initMap = (viewerContainer: HTMLElement) => {
  if (!viewerContainer) {
    console.error('Viewer container is null');
    return;
  }
  console.log('initMap' + viewerContainer);
  const viewer = new SuperMap3D.Viewer(viewerContainer, {
    baseLayerPicker: false,
    geocoder: false, // 是否创建右上角的查询按钮（右上第一个）
    homeButton: false, // 是否创建 home 按钮（右上第二个）
    sceneModePicker: false, // 是否创建右上角的切换地图的按钮（右上第三个）
    navigationHelpButton: false, // 是否创建右上角的导航帮助按钮（右上第五个）
    vrButton: false, // 是否创建右下角的 VR 按钮，默认值为 true
    animation: false, // 是否创建左下角的动画小部件
    fullscreenButton: false, // 是否创建右下角全屏按钮
    timeline: false, // 是否创建最下方的时间线
    scene3DOnly: false, // 仅渲染 3D 场景，不渲染 2D 地图
    shadows: true,
    infoBox: false,
    //   // 三维视图模式，枚举值3
    sceneMode: SuperMap3D.SceneMode.SCENE3D,
    navigation: false, //指南针
    // selectionIndicator: false, //绿色选择框
    contextOptions: {
      contextType: 2, // Webgl2:2 ; WebGPu:3
    },
  });
  //将viewer对象存储在window对象中，方便其他地方调用
  (window as any).__viewer = viewer;
  const scene = viewer.scene;

  //添加影像
  viewer.imageryLayers.addImageryProvider(
    new SuperMap3D.BingMapsImageryProvider({
      url: 'https://dev.virtualearth.net',
      mapStyle: SuperMap3D.BingMapsStyle.AERIAL,
      //当场景出现黑球时可至官网（https://www.bingmapsportal.com/）申请key
      key: 'AraGkBfghounWbX8rAcEEL8VXISh5M7tbxnlGxKocM134GmIr-yr48WBJvfaRaCg',
    }),
  );

  //添加S3M瓦片图层
  const buildPromise = scene.addS3MTilesLayerByScp('http://localhost:8200/realspace/services/3D-CBD-2/rest/realspace/datas/Building@CBD/config', {
    name: 'build',
  });
  const ground1Promise = scene.addS3MTilesLayerByScp('http://localhost:8200/realspace/services/3D-CBD-2/rest/realspace/datas/Ground@CBD/config', {
    name: 'ground1',
  });
  const lakePromise = scene.addS3MTilesLayerByScp('http://localhost:8200/realspace/services/3D-CBD-2/rest/realspace/datas/Lake@CBD/config', {
    name: 'lake',
  });
  const treePromise = scene.addS3MTilesLayerByScp('http://localhost:8200/realspace/services/3D-CBD-2/rest/realspace/datas/Tree@CBD/config', {
    name: 'tree',
  });
  const roadPromise = scene.addS3MTilesLayerByScp('http://localhost:8200/realspace/services/3D-CBD-2/rest/realspace/datas/Xiaopin@CBD/config', {
    name: 'road',
  });
  const bridgePromise = scene.addS3MTilesLayerByScp('http://localhost:8200/realspace/services/3D-CBD-2/rest/realspace/datas/Bridge@CBD/config', {
    name: 'bridge',
  });
  const ground2Promise = scene.addS3MTilesLayerByScp(
    'http://www.supermapol.com/realspace/services/3D-CBD-2/rest/realspace/datas/Ground2@CBD/config',
    {
      name: 'ground2',
    },
  );
  const promiseSet = [ground1Promise, buildPromise, lakePromise, treePromise, roadPromise, bridgePromise];
  SuperMap3D.when.all(promiseSet, function (layer) {
    viewer.camera.flyTo({
      // 相机在WGS84世界坐标系中的最终位置，或是自顶向下视图中可见的矩形区域。
      destination: new SuperMap3D.Cartesian3.fromDegrees(116.4473, 39.89, 600),
      orientation: {
        heading: 0.2732,
        pitch: -0.1583,
        roll: 0,
      },
      duration: 1.5,
    });

    for (let i = 0; i < layer.length; i++) {
      layer[i].selectEnabled = false;
    }
  });

  // viewer.scene.globe.baseColor = SuperMap3D.Color.IVORY;
  // 确保 DOM 渲染完成再隐藏
  setTimeout(() => {
    const logo = document.querySelector('.supermap3d-widget-credits');
    if (logo) logo.remove();
    // viewer._SuperMap3DWidget._creditContainer.style.display = 'none';
  }, 500); // 延迟一点时间以确保元素已加载

  disableSawtooth(viewer);

  viewer.clock.currentTime = SuperMap3D.JulianDate.fromDate(new Date(2025, 6, 4, 12)); // 设定比当前时间更好的光照效果
  //帧率显示
  scene.debugShowFramesPerSecond = false;
  // scene.shadowMap.darkness = 1.275; //设置第二重烘焙纹理的效果（明暗程度）
  //设置太阳光的颜色与强度
  scene.lightSource.sunLightColor = new SuperMap3D.Color(1 * 2, 1 * 2, 1 * 2, 1);
  scene.sun.show = true;

  //添加地形
  // viewer.terrainProvider = new SuperMap3D.SuperMapTerrainProvider({
  //   url: URL_CONFIG.SiChuan_TERRAIN,
  //   isSct: true,
  //   invisibility: true
  // })

  return viewer;
};

// 设置自定义天空盒
export const createOutSkyBox = (viewer, show) => {
  // 外天空盒
  viewer.scene.skyBox = new SuperMap3D.SkyBox({
    sources: {
      positiveX: '/images/skybox1/tycho2t3_80_px.jpg',
      negativeX: '/images/skybox1/tycho2t3_80_mx.jpg',
      positiveY: '/images/skybox1/tycho2t3_80_py.jpg',
      negativeY: '/images/skybox1/tycho2t3_80_my.jpg',
      positiveZ: '/images/skybox1/tycho2t3_80_pz.jpg',
      negativeZ: '/images/skybox1/tycho2t3_80_mz.jpg',
    },
    show: show,
  });
};

/**
 * 开启抗锯齿
 */
export const disableSawtooth = (viewer) => {
  // 是否支持图像渲染像素化处理
  if (SuperMap3D.FeatureDetection.supportsImageRenderingPixelated()) {
    //将 viewer渲染分辨率比例设置为设备的物理像素与 CSS 像素的比例 ，渲染的图像能够以更高的像素密度显示，从而避免图像模糊或锯齿。
    viewer.resolutionScale = window.devicePixelRatio;
  }
  // 开启抗锯齿
  viewer.scene.postProcessStages.fxaa.enabled = true;
};

/**
 * 启动相机信息监听器 获取相机位置，姿态等
 * @param viewer SuperMap3D Viewer 实例
 * @param onUpdate 回调函数（每次更新时调用）
 * 新增了限流功能 通过lastUpdate判断是否在100ms内更新
 */

export interface CameraInfo {
  longitude: string;
  latitude: string;
  height: string;
  heading: string;
  pitch: string;
  roll: string;
  cartesian3Position?: any;
}

let lastUpdate = 0;

export function startCameraInfoTracking(viewer, onUpdate: (info: CameraInfo) => void) {
  viewer.scene.postRender.addEventListener(() => {
    const now = Date.now();
    if (now - lastUpdate < 100) return; // 每 100ms 更新一次
    lastUpdate = now;
    // 获取位置 wgs84的地心坐标系，x,y坐标值以弧度来表示
    const position = viewer.scene.camera.positionCartographic; //with longitude and latitude expressed in radians and height in meters.
    const cameraInfo: CameraInfo = {
      // 弧度转经纬度
      longitude: SuperMap3D.Math.toDegrees(position.longitude).toFixed(6),
      latitude: SuperMap3D.Math.toDegrees(position.latitude).toFixed(6),
      height: position.height,
      // 获取 相机姿态信息
      heading: SuperMap3D.Math.toDegrees(viewer.camera.heading),
      pitch: SuperMap3D.Math.toDegrees(viewer.camera.pitch),
      roll: SuperMap3D.Math.toDegrees(viewer.camera.roll),
      cartesian3Position: viewer.scene.camera.position,
    };
    onUpdate(cameraInfo);
  });
}

/**
 * 点击鼠标左键获取点位信息
 * @param {*} viewer
 */

export const getMousePosition = (viewer, callback) => {
  //首先移除之前添加的点
  // 创建ScreenSpaceEventHandler实例
  const handler = new SuperMap3D.ScreenSpaceEventHandler(viewer.canvas);
  // 监听鼠标左键点击事件
  handler.setInputAction((click) => {
    // 获取点击位置的笛卡尔坐标
    const cartesian = viewer.camera.pickEllipsoid(click.position, viewer.scene.globe.ellipsoid);
    if (cartesian || SuperMap3D.defined(cartesian)) {
      //将笛卡尔坐标转换为地理坐标
      const cartographic = SuperMap3D.Cartographic.fromCartesian(cartesian);
      // 计算经纬度坐标
      const longitude = SuperMap3D.Math.toDegrees(cartographic.longitude).toFixed(6);
      const latitude = SuperMap3D.Math.toDegrees(cartographic.latitude).toFixed(6);
      const height = cartographic.height;
      // 显示点击点的经纬度坐标
      // console.log(`经度: ${longitude}, 纬度: ${latitude}, 高度: ${height}`);
      // 显示点击点的笛卡尔坐标
      // console.log('点击点的笛卡尔坐标：', cartesian);
      // 显示点位信息
      // alert(`您点击的位置是：\n经度: ${longitude}, 纬度: ${latitude}, 高度: ${height}`);
      //在点击位置添加对应点
      // viewer.entities.add(
      //   new SuperMap3D.Entity({
      //     point: new SuperMap3D.PointGraphics({
      //       color: new SuperMap3D.Color(1, 1, 0),
      //       pixelSize: 10,
      //       outlineColor: new SuperMap3D.Color(0, 1, 1)
      //     }),
      //     position: SuperMap3D.Cartesian3.fromDegrees(longitude, latitude, height + 0.5)
      //   })
      // );
      callback({ longitude, latitude, height });
    }
  }, SuperMap3D.ScreenSpaceEventType.RIGHT_CLICK);
};
